import Dictdata from "@/entity/system/dictdata/Dictdata";
import http from "./httpRequest";
import { toPromise } from "@xuekl/cli-utils";

export default class DictStore {
	// 字典请求记录
	private static dictRequestRecord = {}
	private static dictMap = {}

	private static setDict(type: string, dicts: Dictdata[]) {
		DictStore.dictMap[type] = dicts
	}

	public static async getDict(type: string) {
		if (DictStore.dictRequestRecord[type]) {
			return await toPromise(() => DictStore.dictMap[type])
		}
		DictStore.dictRequestRecord[type] = 'record'

		if (!DictStore.dictMap[type]) {
			return await DictStore.requestDict(type);
		}
		return DictStore.dictMap[type];
	}


	public static async getDictLabel(type: string, dictValue: string) {
		const dictBeans: Dictdata[] = await DictStore.getDict(type);
		for (let dictBean of dictBeans) {
			if (dictBean.dictValue == dictValue) {
				return dictBean.dictLabel;
			}
		}
		return "";
	}

	public static async requestDict(type: string) {
		const { data } = await http({
			url: http.adornUrl("/base/mgt/dictData/dictDataSelector/" + type),
			method: 'get'
		})

		if (data.code === '0') {
			DictStore.setDict(type, data.data)
			return data.data
		}
		return []
	}
}